package com.aternity.ipresolve;

import org.apache.commons.lang.text.StrTokenizer;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author Bashan
 */
public class IpUtils {
    public static final String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
    public static final Pattern pattern = Pattern.compile("^(?:" + _255 + "\\.){3}" + _255 + "$");
    public static final long L10 = ipV4ToLong("10.0.0.0");
    public static final long L10255 = ipV4ToLong("10.255.255.255");
    public static final long L17216 = ipV4ToLong("172.16.0.0");
    public static final long L17231 = ipV4ToLong("172.31.255.255");
    public static final long L192168S = ipV4ToLong("192.168.0.0");
    public static final long L192168E = ipV4ToLong("192.168.255.255");

    public static String longToIpV4(long longIp) {
        int octet3 = (int) ((longIp >> 24) % 256);
        int octet2 = (int) ((longIp >> 16) % 256);
        int octet1 = (int) ((longIp >> 8) % 256);
        int octet0 = (int) ((longIp) % 256);
        return octet3 + "." + octet2 + "." + octet1 + "." + octet0;
    }

    private static Map<String, Long> cache = new HashMap<>();

    public static long ipV4ToLong(String ip) {
        String[] octets = ip.split("\\.");
        return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) +
                (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]);
    }

    public static boolean isIPv4Private(String ip) {
        long longIp = ipV4ToLong(ip);
        return (longIp >= L10 && longIp <= L10255) ||
                (longIp >= L17216 && longIp <= L17231) ||
                longIp >= L192168S && longIp <= L192168E;
    }

    public static boolean isIPv4Valid(String ip) {
        return pattern.matcher(ip).matches();
    }


    public static String getIpFromRequest(String ip) {

        boolean found = false;

        StrTokenizer tokenizer = new StrTokenizer(ip, ",");
        while (tokenizer.hasNext()) {
            ip = tokenizer.nextToken().trim();
            if (isIPv4Valid(ip) && !isIPv4Private(ip)) {
                found = true;
                break;
            }
        }

        return ip;
    }
}